package com.nari.ncps.screen.service.impl.electric;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.electric.ElectricOpermonPlant;
import com.nari.ncps.screen.mapper.electric.ElectricProdoperCoalConsumeLrMapper;
import com.nari.ncps.screen.service.electric.ElectricOpermonPlantService;
import com.nari.ncps.screen.service.electric.ElectricProdoperCoalConsumeLrService;
import com.nari.ncps.screen.entity.electric.ElectricProdoperCoalConsumeLr;
import com.nari.ncps.screen.vo.electric.OperationLevelVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 火电生产实时负荷表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricProdoperCoalConsumeLrServiceImpl extends ServiceImpl<ElectricProdoperCoalConsumeLrMapper, ElectricProdoperCoalConsumeLr> implements ElectricProdoperCoalConsumeLrService {

    @Resource
    private ElectricOpermonPlantService electricOpermonPlantService;

    /**
     * 火电生产实时负荷表
     * 查询数据库中最新的两天数据（今日和昨日）
     * @return
     */
    @Override
    public List<ElectricProdoperCoalConsumeLr> prodoperCoalConsume() {
        // 1. 先查询数据库中最新的日期
        QueryWrapper<ElectricProdoperCoalConsumeLr> latestWrapper = new QueryWrapper<>();
        latestWrapper.select("year", "month", "day")
                .orderByDesc("year", "month", "day")
                .last("LIMIT 1");
        ElectricProdoperCoalConsumeLr latest = getOne(latestWrapper);
        
        if (latest == null) {
            return new ArrayList<>();
        }
        
        // 2. 获取今日（最新日期）的数据
        QueryWrapper<ElectricProdoperCoalConsumeLr> todayWrapper = new QueryWrapper<>();
        todayWrapper.eq("year", latest.getYear())
                .eq("month", latest.getMonth())
                .eq("day", latest.getDay())
                .orderByAsc("hour");
        List<ElectricProdoperCoalConsumeLr> todayData = list(todayWrapper);
        
        // 3. 获取昨日日期
        LocalDate todayDate = LocalDate.of(latest.getYear(), latest.getMonth(), latest.getDay());
        LocalDate yesterdayDate = todayDate.minusDays(1);
        
        // 4. 查询昨日数据
        QueryWrapper<ElectricProdoperCoalConsumeLr> yesterdayWrapper = new QueryWrapper<>();
        yesterdayWrapper.eq("year", yesterdayDate.getYear())
                .eq("month", yesterdayDate.getMonthValue())
                .eq("day", yesterdayDate.getDayOfMonth())
                .orderByAsc("hour");
        List<ElectricProdoperCoalConsumeLr> yesterdayData = list(yesterdayWrapper);
        
        // 5. 合并今日和昨日数据
        List<ElectricProdoperCoalConsumeLr> result = new ArrayList<>();
        result.addAll(todayData);
        result.addAll(yesterdayData);
        
        return result;
    }

    /**
     * 查询运行水平信息
     * @param orgCode 单位编码（可选）
     * @return 运行水平信息列表，返回20条分钟级别的数据
     */
    @Override
    public List<OperationLevelVO> getOperationLevel(String orgCode) {
        // 获取当前时间
        Date now = new Date();
        Integer year = DateUtil.year(now);
        Integer month = DateUtil.month(now) + 1;
        Integer day = DateUtil.dayOfMonth(now);

        List<OperationLevelVO> resultList = new ArrayList<>();

        // 1. 查询实时负荷数据（最近20条）
        QueryWrapper<ElectricProdoperCoalConsumeLr> loadWrapper = new QueryWrapper<>();
        loadWrapper.eq("year", year);
        loadWrapper.eq("month", month);
        loadWrapper.eq("day", day);
        if (orgCode != null && !orgCode.isEmpty()) {
            loadWrapper.eq("org_code", orgCode);
        }
        loadWrapper.orderByDesc("hour");
        loadWrapper.last("LIMIT 20");

        List<ElectricProdoperCoalConsumeLr> loadList = list(loadWrapper);

        // 如果当天没有数据，查询最近的数据
        if (loadList == null || loadList.isEmpty()) {
            QueryWrapper<ElectricProdoperCoalConsumeLr> fallbackWrapper = new QueryWrapper<>();
            if (orgCode != null && !orgCode.isEmpty()) {
                fallbackWrapper.eq("org_code", orgCode);
            }
            fallbackWrapper.orderByDesc("year", "month", "day", "hour");
            fallbackWrapper.last("LIMIT 20");
            loadList = list(fallbackWrapper);
        }

        // 如果还是没有数据，返回空列表
        if (loadList == null || loadList.isEmpty()) {
            return resultList;
        }

        // 反转列表，使其按时间升序
        java.util.Collections.reverse(loadList);

        // 2. 查询电厂的装机容量
        BigDecimal installedCapacity = BigDecimal.ZERO;
        String plantCode = null;

        if (!loadList.isEmpty()) {
            ElectricProdoperCoalConsumeLr firstLoad = loadList.get(0);
            plantCode = firstLoad.getOrgCode();

            // 查询电厂装机容量
            QueryWrapper<ElectricOpermonPlant> plantWrapper = new QueryWrapper<>();
            plantWrapper.eq("year", year);
            plantWrapper.eq("month", month);
            plantWrapper.eq("date_type", 1); // 月数据
            if (plantCode != null && !plantCode.isEmpty()) {
                plantWrapper.eq("org_code", plantCode);
            }
            plantWrapper.orderByDesc("update_time");
            plantWrapper.last("LIMIT 1");

            ElectricOpermonPlant plant = electricOpermonPlantService.getOne(plantWrapper);
            if (plant != null && plant.getTotalCapacity() != null) {
                installedCapacity = plant.getTotalCapacity().multiply(new BigDecimal("10")); // 万千瓦转换为MW
            }
        }

        // 3. 基于实时负荷数据生成20条分钟级别的数据
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        
        for (int i = 0; i < Math.min(20, loadList.size()); i++) {
            ElectricProdoperCoalConsumeLr load = loadList.get(i);
            OperationLevelVO vo = new OperationLevelVO();
            
            vo.setPowerPlantCode(load.getOrgCode());
            vo.setPowerPlantName(load.getOrgName());
            
            // 生成时间（每3分钟一个数据点）
            int minuteOffset = i * 3;
            Date recordTime = DateUtil.offsetMinute(DateUtil.beginOfDay(now), load.getHour() * 60 + minuteOffset);
            vo.setRecordTime(timeFormat.format(recordTime));
            
            // 实时负荷（MW）- 注意数据库中是MW，不需要转换
            BigDecimal currentLoad = load.getCurrentLoad() != null ? load.getCurrentLoad() : BigDecimal.ZERO;
            vo.setCurrentLoad(currentLoad);
            
            // 计算负荷率 = (当前负荷 / 装机容量) * 100
            BigDecimal loadRate = BigDecimal.ZERO;
            if (installedCapacity.compareTo(BigDecimal.ZERO) > 0 && currentLoad.compareTo(BigDecimal.ZERO) > 0) {
                loadRate = currentLoad.divide(installedCapacity, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, RoundingMode.HALF_UP);
            }
            vo.setLoadRate(loadRate);
            
            resultList.add(vo);
        }

        return resultList;
    }
}